import { ref, onMounted, onUnmounted } from 'vue'

// 全局全屏状态
const isFullscreen = ref(false)

export function useFullscreen() {
  // 全屏切换功能
  const toggleFullscreen = () => {
    if (!document.fullscreenElement) {
      // 进入全屏
      document.documentElement.requestFullscreen().then(() => {
        isFullscreen.value = true
      }).catch(err => {
        console.error('无法进入全屏模式:', err)
      })
    } else {
      // 退出全屏
      document.exitFullscreen().then(() => {
        isFullscreen.value = false
      }).catch(err => {
        console.error('无法退出全屏模式:', err)
      })
    }
  }

  // 监听全屏状态变化
  const handleFullscreenChange = () => {
    isFullscreen.value = !!document.fullscreenElement
  }

  // 监听ESC键退出全屏
  const handleKeyDown = (event) => {
    if (event.key === 'Escape' && isFullscreen.value) {
      isFullscreen.value = false
    }
  }

  onMounted(() => {
    document.addEventListener('fullscreenchange', handleFullscreenChange)
    document.addEventListener('keydown', handleKeyDown)
  })

  onUnmounted(() => {
    document.removeEventListener('fullscreenchange', handleFullscreenChange)
    document.removeEventListener('keydown', handleKeyDown)
  })

  return {
    isFullscreen,
    toggleFullscreen
  }
}
